using DemoWebapi01.Entities;
using DemoWebapi01.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace DemoWebapi01.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class CategoryController : ControllerBase
    {
        private readonly MyDbContext _context;

        public CategoryController(MyDbContext context)
        {
            _context = context;
        }

        /// <summary>
        /// 获取所有知识点分类
        /// </summary>
        [HttpGet]
        public async Task<ActionResult<IEnumerable<Category>>> GetCategories()
        {
            return await _context.Categories
                .OrderBy(c => c.DisplayOrder)
                .ToListAsync();
        }
        /// <summary>
        /// 获取单个知识点分类
        /// </summary>
        [HttpGet("{id}")]
        public async Task<ActionResult<Category>> GetCategory(Guid id)
        {
            var category = await _context.Categories.FindAsync(id);

            if (category == null)
            {
                return NotFound("分类不存在");
            }

            return category;
        }

        /// <summary>
        /// 创建新的知识点分类
        /// </summary>
        [HttpPost]
        public async Task<ActionResult<Category>> CreateCategory(CategoryCreateRequest request)
        {
            // 参数验证
            if (string.IsNullOrEmpty(request.Name))
            {
                return BadRequest("分类名称不能为空");
            }

            // 检查分类名是否已存在
            if (_context.Categories.Any(c => c.Name == request.Name))
            {
                return BadRequest("该分类名称已存在");
            }

            // 创建新分类
            var category = new Category
            {
                CategoryID = Guid.NewGuid(),
                Name = request.Name,
                Icon = request.Icon,
                Description = request.Description,
                DisplayOrder = request.DisplayOrder
            };

            _context.Categories.Add(category);
            await _context.SaveChangesAsync();

            return CreatedAtAction(nameof(GetCategory), new { id = category.CategoryID }, category);
        }

        /// <summary>
        /// 更新知识点分类
        /// </summary>
        [HttpPut("{id}")]
        public async Task<IActionResult> UpdateCategory(Guid id, CategoryUpdateRequest request)
        {
            var category = await _context.Categories.FindAsync(id);
            if (category == null)
            {
                return NotFound("分类不存在");
            }

            // 检查分类名是否已存在（排除当前分类）
            if (!string.IsNullOrEmpty(request.Name) &&
                request.Name != category.Name &&
                _context.Categories.Any(c => c.Name == request.Name))
            {
                return BadRequest("该分类名称已存在");
            }

            // 更新分类信息
            if (!string.IsNullOrEmpty(request.Name))
                category.Name = request.Name;

            category.Icon = request.Icon ?? category.Icon;
            category.Description = request.Description ?? category.Description;

            if (request.DisplayOrder.HasValue)
                category.DisplayOrder = request.DisplayOrder.Value;

            _context.Entry(category).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!CategoryExists(id))
                {
                    return NotFound("分类不存在");
                }
                else
                {
                    throw;
                }
            }

            return Ok(category);
        }

        /// <summary>
        /// 删除知识点分类
        /// </summary>
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteCategory(Guid id)
        {
            var category = await _context.Categories.FindAsync(id);
            if (category == null)
            {
                return NotFound("分类不存在");
            }

            _context.Categories.Remove(category);
            await _context.SaveChangesAsync();

            return Ok("分类删除成功");
        }

        private bool CategoryExists(Guid id)
        {
            return _context.Categories.Any(e => e.CategoryID == id);
        }
    }
}